package com.mind.core.net.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mind.core.net.handler.HandlerManager;
import com.mind.core.net.msg.Message;

public class GameDecoder extends ByteToMessageDecoder {
	private final static Logger logger = LoggerFactory.getLogger("decoder");
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out)
			throws Exception {
		int leftNum=in.readableBytes();
		if(leftNum<Message.MIN_MESSAGE_LENGTH){
			return ;
		}
		int len=in.readShort();
		if(in.readableBytes()<(len-Message.HEADER_LEN_BYTES)){
			return ;
		}
		short type=in.readShort();
		ByteBuf buf=ctx.alloc().buffer(len);
		buf.writeShort(len);
		buf.writeShort(type);
		buf.writeBytes(in,len-Message.MIN_MESSAGE_LENGTH);
		Message msg=HandlerManager.createMessage(type);
		msg.setBuffer(buf);
		if(!msg.read()){
			throw new Exception("decoder  wrong!message code="+type);
		}
		out.add(msg);
	}
}
